export class TokenHandler {
  private static authorTokenKey = 'Authorization'
  private static authorRefreshTokenKey = 'refreshToken'
  /**
   * @fn: 设置验证的token
   */
  public static setToken(tk: string, expire: number) {
    if (!tk) return null
    this.setExpire(this.authorTokenKey, tk, expire)
  }
  /**
   * @fn: 获取验证的token
   */
  public static getToken(): string | void {
    const token = this.getExpire(this.authorTokenKey)
    let res = token === null ? console.warn('token值为null') : 'Bearer ' + token
    return res
  }
  /**
   * @fn: 设置refreshToken
   */
  public static setRefreshToken(refreshToken: string) {
    if (!refreshToken) return null
    localStorage.setItem(this.authorRefreshTokenKey, refreshToken)
  }
  /**
   * @fn: 获取refreshToken
   */
  public static getRefreshToken() {
    let res = localStorage.getItem(this.authorRefreshTokenKey)
    return res
  }
  /**
   * @fn:Storage.prototype.setExpire
   */
  public static setExpire(key: string, value: string, expire: number) {
    let obj = {
      data: value,
      time: Date.now(),
      expire,
    }
    localStorage.setItem(key, JSON.stringify(obj))
  }
  /**
   * @fn:Storage.prototype.getExpire
   */
  public static getExpire(key: string) {
    let val = localStorage.getItem(key)
    if (!val) return null
    const { time, expire, data } = JSON.parse(val)
    if (Date.now() - time > expire * 1000) {
      localStorage.removeItem(key)
      return null
    }
    return data
  }
}
